package jgl.vajra.driver.part.web;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import java.util.ArrayList;
import java.util.List;

import jgl.vajra.driver.R;

/**
 * Android应用更新弹窗
 * 用于向用户展示新版本信息并提供更新选项
 */
public class UpdateDialog extends DialogFragment {

    // 回调接口
    public interface UpdateDialogListener {
        void onUpdateNowClicked();

        void onRemindLaterClicked();

        void onSkipVersionClicked();
    }

    // 弹窗类型
    public enum DialogType {
        NORMAL,       // 普通更新
        FORCE,        // 强制更新
        RECOMMENDED   // 推荐更新
    }

    // 参数
    private String mCurrentVersion;
    private String mLatestVersion;
    private String mUpdateUrl;
    private List<String> mUpdateContents;
    private DialogType mDialogType;
    private UpdateDialogListener mListener;

    // 工厂方法创建实例
    public static UpdateDialog newInstance(String currentVersion, String latestVersion,
                                           String updateUrl, List<String> updateContents,
                                           DialogType dialogType) {
        UpdateDialog dialog = new UpdateDialog();
        Bundle args = new Bundle();
        args.putString("currentVersion", currentVersion);
        args.putString("latestVersion", latestVersion);
        args.putString("updateUrl", updateUrl);
        args.putStringArrayList("updateContents", new ArrayList<>(updateContents));
        args.putSerializable("dialogType", dialogType);
        dialog.setArguments(args);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 从参数中获取数据
        if (getArguments() != null) {
            mCurrentVersion = getArguments().getString("currentVersion");
            mLatestVersion = getArguments().getString("latestVersion");
            mUpdateUrl = getArguments().getString("updateUrl");
            mUpdateContents = getArguments().getStringArrayList("updateContents");
            mDialogType = (DialogType) getArguments().getSerializable("dialogType");
        }

        // 设置弹窗样式
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.UpdateDialogTheme);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Context context = getActivity();
        if (context == null) {
            return super.onCreateDialog(savedInstanceState);
        }

        // 创建AlertDialog.Builder
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        // 加载自定义布局
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_update, null);

        // 初始化视图
        initViews(view);

        // 设置视图
        builder.setView(view);

        // 创建对话框
        AlertDialog dialog = builder.create();

        // 设置点击外部是否可取消
        dialog.setCanceledOnTouchOutside(mDialogType != DialogType.FORCE);
        dialog.setCancelable(mDialogType != DialogType.FORCE);

        return dialog;
    }

    /**
     * 初始化视图
     */
    private void initViews(View view) {
        // 版本信息
        TextView tvVersionInfo = view.findViewById(R.id.tv_version_info);
        String versionText = String.format("当前版本: %s\n最新版本: %s",
                mCurrentVersion, mLatestVersion);
        tvVersionInfo.setText(versionText);

        // 更新内容
        TextView tvUpdateContent = view.findViewById(R.id.tv_update_content);
        if (mUpdateContents != null && !mUpdateContents.isEmpty()) {
            StringBuilder contentBuilder = new StringBuilder();
            for (String content : mUpdateContents) {
                contentBuilder.append("• ").append(content).append("\n");
            }
            tvUpdateContent.setText(contentBuilder.toString().trim());
        } else {
            tvUpdateContent.setText("优化用户体验，修复已知问题");
        }

        // 立即更新按钮
        Button btnUpdateNow = view.findViewById(R.id.btn_update_now);
        btnUpdateNow.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onUpdateNowClicked();
            }
            updateApp();
            dismiss();
        });

        // 稍后提醒按钮
        Button btnRemindLater = view.findViewById(R.id.btn_remind_later);
        btnRemindLater.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onRemindLaterClicked();
            }
            dismiss();
        });

        // 跳过此版本按钮
        Button btnSkipVersion = view.findViewById(R.id.btn_skip_version);
        btnSkipVersion.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.onSkipVersionClicked();
            }
            dismiss();
        });

        // 根据弹窗类型设置按钮显示状态
        if (mDialogType == DialogType.FORCE) {
            btnRemindLater.setVisibility(View.GONE);
            btnSkipVersion.setVisibility(View.GONE);
        } else if (mDialogType == DialogType.RECOMMENDED) {
            btnSkipVersion.setVisibility(View.GONE);
        }
    }

    /**
     * 执行应用更新
     */
    private void updateApp() {
        Context context = getActivity();
        if (context == null || TextUtils.isEmpty(mUpdateUrl)) {
            return;
        }

        try {
            // 跳转到应用商店或下载链接
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mUpdateUrl));
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "无法打开更新链接，请稍后重试", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 设置回调监听器
     */
    public void setUpdateDialogListener(UpdateDialogListener listener) {
        mListener = listener;
    }

    /**
     * 显示更新弹窗
     */
    public static void showUpdateDialog(FragmentManager activity, String currentVersion,
                                        String latestVersion, String updateUrl,
                                        List<String> updateContents, DialogType dialogType,
                                        UpdateDialogListener listener) {


        try {
            UpdateDialog dialog = UpdateDialog.newInstance(
                    currentVersion, latestVersion, updateUrl, updateContents, dialogType);
            dialog.setUpdateDialogListener(listener);
            dialog.show(activity, "UpdateDialog");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

